/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.cef.spi.common;

import com.inspur.edp.cef.api.manager.ICefValueObjManager;
import com.inspur.edp.cef.entity.entity.IValueObjData;
import com.inspur.edp.udt.api.IUdtFactory;
import com.inspur.edp.udt.entity.ISimpleUdtData;
import com.inspur.edp.udt.entity.IUdtData;
import io.iec.edp.caf.runtime.config.CefBeanUtil;
import java.util.Objects;

public final class UdtManagerUtil {

  static {
    udtFactory = CefBeanUtil.getAppCtx().getBean(IUdtFactory.class);
  }

  private static IUdtFactory udtFactory;

  public static IUdtFactory getUdtFactory() {
    if (udtFactory == null) {
      udtFactory = CefBeanUtil.getAppCtx().getBean(IUdtFactory.class);
    }
    return udtFactory;
  }

  public static <T extends IUdtData> T createData(String configId) {
    Objects.requireNonNull(configId, "configId");
    T rez = (T) getUdtFactory().createManager(configId).createDataType();
    return rez;
  }

  public static <T extends ISimpleUdtData<TValue>, TValue> T createData(String configId,
      TValue value) {
    Objects.requireNonNull(configId, "configId");
    T rez = (T) getUdtFactory().createManager(configId).createDataType();
//    if (value != null) {
      rez.setValue(value);
//    }
    return rez;
  }

  public static <T extends ICefValueObjManager> T createManager(String configId) {
    Objects.requireNonNull(configId, "configId");
    return (T) getUdtFactory().createManager(configId);
  }

  public static <T extends ICefValueObjManager> T createValueObject(String configId,
      IValueObjData data) {
    Objects.requireNonNull(configId, "configId");
    return (T) ((ICefValueObjManager) getUdtFactory().createManager(configId))
        .createValueObject(data);
  }
}
